package gateway

import (
	"io"
	"net"
	"time"
	"tinp/common"
	"tinp/mylog"
)

type GateWay struct {
	addr       string
	sessionMrg *SessionManager
}

func NewGateway(addr string, sessionMrg *SessionManager) *GateWay {
	gw := &GateWay{
		addr:       addr,
		sessionMrg: sessionMrg,
	}
	go gw.checkOnlineInterval()
	return gw
}

func (w *GateWay) ListenAndServe() error {
	listen, err := net.Listen("tcp", w.addr)
	if err != nil {
		return err
	}
	// defer listen.Close()
	for {
		conn, err := listen.Accept()
		if err != nil && err != io.EOF {
			return err
		}
		go w.handleConn(conn)
	}
}
func (w *GateWay) handleConn(conn net.Conn) {
	handshakeReq := &common.HandshakeReq{}
	err := handshakeReq.Decode(conn)
	if err != nil {
		mylog.Logger.Errorf("decode handshare fail: %v", err)
		return
	}
	mylog.Logger.Infof("与客户端建立连接成功, 地址为: %s, 客户端Id为: %s", conn.RemoteAddr().String(), handshakeReq.ClientId)
	// 创建session
	w.sessionMrg.CreateSession(handshakeReq.ClientId, conn)
}
func (w *GateWay) checkOnlineInterval() {
	// 构建一个定时器 每2秒向tick.C通道写入数据
	tick := time.NewTicker(time.Second * 2)
	defer tick.Stop()
	for range tick.C {
		// 删除已关闭的连接
		w.sessionMrg.DeleteClosedConn()
	}
}
